/**
  ******************************************************************************
  * @file    main.c
  * @author  MCU Application Team
  * @brief   Main program body
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2023 Puya Semiconductor Co.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by Puya under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2016 STMicroelectronics.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by ST under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  */

/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "py32f092xx_ll_Start_Kit.h"

/* Private define ------------------------------------------------------------*/
/* Defines related to Clock configuration */
/* ck_apre=LSIFreq/(ASYNC prediv + 1) with LSIFreq=32768Hz RC */
#define RTC_ASYNCH_PREDIV          ((uint32_t)0x7F)
/* ck_spre=ck_apre/(SYNC prediv + 1) = 1 Hz */
#define RTC_SYNCH_PREDIV           ((uint32_t)0x00FF)

/* Private variables ---------------------------------------------------------*/
/* Buffers used for displaying Time and Date */
uint8_t aShowTime[16] = "hh:ms:ss";
uint8_t aShowDate[16] = "dd/mm/aaaa";
uint8_t aShowTimeStamp[16] = "hh:ms:ss";
uint8_t aShowDateStamp[16] = "dd-mm-yyyy";

/* Private user code ---------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
static void APP_SystemClockConfig(void);
static void APP_RTC_Init(void);
static void APP_RTC_TimeStampConfig(void);
static void APP_RTC_CalendarShow(void);

/**
  * @brief  Main program.
  * @param  None
  * @retval int
  */
int main(void)
{
  /* Enable SYSCFG and PWR clock */
  LL_APB1_GRP2_EnableClock(LL_APB1_GRP2_PERIPH_SYSCFG);
  LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_PWR);

  /* Configure system clock */
  APP_SystemClockConfig();
  
  /* Initialize debugging serial port (used by printf) */
  BSP_UART_Config();
  
  /* Initialize RTC */
  APP_RTC_Init();
  
  /* Configure RTC Timestamp */
  APP_RTC_TimeStampConfig();
  
  while (1)
  {
    /* Display the updated Time and Date */
    APP_RTC_CalendarShow();
  }
}

/**
  * @brief  Configure system clock
  * @param  None
  * @retval None
  */
static void APP_SystemClockConfig(void)
{
  /* Enable HSI */
  LL_RCC_HSI_Enable();
  while(LL_RCC_HSI_IsReady() != 1)
  {
  }
  /* Enable access to the backup domain */
  LL_PWR_EnableBkUpAccess();
  
  /* Reset backup domain */
  LL_RCC_ForceBackupDomainReset();
  LL_RCC_ReleaseBackupDomainReset();
  
  /* Enable LSI */
  LL_RCC_LSI_Enable();
  
  /* Wait till LSI is ready */
  while(LL_RCC_LSI_IsReady() != 1)
  {
  }
  
  /* Set AHB prescaler: HCLK = SYSCLK */
  LL_RCC_SetAHBPrescaler(LL_RCC_SYSCLK_DIV_1);

  /* Select HSISYS as system clock source */
  LL_RCC_SetSysClkSource(LL_RCC_SYS_CLKSOURCE_HSISYS);
  while(LL_RCC_GetSysClkSource() != LL_RCC_SYS_CLKSOURCE_STATUS_HSISYS)
  {
  }

  /* Set APB prescaler: PCLK = HCLK */
  LL_RCC_SetAPB1Prescaler(LL_RCC_APB1_DIV_1);
  LL_Init1msTick(8000000);

  /* Update the SystemCoreClock global variable(which can be updated also through SystemCoreClockUpdate function) */
  LL_SetSystemCoreClock(8000000);
  
  /* Set RTC Clock Source */
  LL_RCC_SetRTCClockSource(LL_RCC_RTC_CLKSOURCE_LSI);
  
  /* Enable RTC */
  LL_RCC_EnableRTC();
}

/**
  * @brief RTC Initialization Function
  * @param None
  * @retval None
  */
static void APP_RTC_Init(void)
{
  LL_RTC_InitTypeDef RTC_InitStruct = {0};
  LL_RTC_TimeTypeDef RTC_TimeStruct = {0};
  LL_RTC_DateTypeDef RTC_DateStruct = {0};
  
  /* Initialize RTC and set the Time and Date */
  RTC_InitStruct.HourFormat = LL_RTC_HOURFORMAT_24HOUR;
  RTC_InitStruct.AsynchPrescaler = RTC_ASYNCH_PREDIV;
  RTC_InitStruct.SynchPrescaler = RTC_SYNCH_PREDIV;
  LL_RTC_Init(RTC, &RTC_InitStruct);

  RTC_TimeStruct.Hours = 0x11;
  RTC_TimeStruct.Minutes = 0x59;
  RTC_TimeStruct.Seconds = 0x55;
  LL_RTC_TIME_Init(RTC, LL_RTC_FORMAT_BCD, &RTC_TimeStruct);
  
  RTC_DateStruct.WeekDay = LL_RTC_WEEKDAY_FRIDAY;
  RTC_DateStruct.Month = LL_RTC_MONTH_DECEMBER;
  RTC_DateStruct.Day = 0x29;
  RTC_DateStruct.Year = 0x16;
  LL_RTC_DATE_Init(RTC, LL_RTC_FORMAT_BCD, &RTC_DateStruct);
  
  /* RTC interrupt */
  NVIC_SetPriority(RTC_TAMP_IRQn, 0);
  NVIC_EnableIRQ(RTC_TAMP_IRQn);
}

/**
  * @brief  Activate timestamp.
  * @param  None
  * @retval None
  */
static void APP_RTC_TimeStampConfig(void)
{
  /*##-1- Disable RTC registers write protection ############################*/
  LL_RTC_DisableWriteProtection(RTC);
  
  /*##-2- Configure the Time Stamp peripheral ###############################*/
  /*  RTC TimeStamp generation: TimeStamp Rising Edge on RTC_TS Pin */
  LL_RTC_TS_SetActiveEdge(RTC, LL_RTC_TIMESTAMP_EDGE_RISING);
  LL_RTC_TS_Enable(RTC);
  /* LL_RTC_SetAlarmOutEvent(RTC, LL_RTC_ALARMOUT_DISABLE); */
  /* LL_RTC_DisableTamperOutput(RTC); */
  /* LL_RTC_TAMPER_Disable(RTC, LL_RTC_TAMPER_1); */
  /* LL_RTC_CAL_SetOutputFreq(RTC, LL_RTC_CALIB_OUTPUT_NONE); */

  /* Enable IT timestamp */
  LL_RTC_EnableIT_TS(RTC);
  
  /* RTC timestamp Interrupt Configuration: EXTI configuration */
  LL_EXTI_EnableIT(LL_EXTI_LINE_20);
}

/**
  * @brief  Timestamp callback
  * @param  hrtc : hrtc handle
  * @retval None
  */
void APP_RTCTimeStampCallback(void)
{
  /* Display time Format : hh:mm:ss */
  sprintf((char *)aShowTimeStamp, "%.2d:%.2d:%.2d", __LL_RTC_CONVERT_BCD2BIN(LL_RTC_TS_GetHour(RTC)),
          __LL_RTC_CONVERT_BCD2BIN(LL_RTC_TS_GetMinute(RTC)),
          __LL_RTC_CONVERT_BCD2BIN(LL_RTC_TS_GetSecond(RTC)));
  printf("%s\r\n", aShowTimeStamp);
  /* Display date Format : mm-dd */
  sprintf((char *)aShowDateStamp, "%.2d-%.2d-%.2d", __LL_RTC_CONVERT_BCD2BIN(LL_RTC_TS_GetMonth(RTC)), 
          __LL_RTC_CONVERT_BCD2BIN(LL_RTC_TS_GetDay(RTC)), 2016);
  printf("%s\r\n", aShowDateStamp);
}

/**
  * @brief  Display the current time and date.
  * @param  None
  * @retval None
  */
static void APP_RTC_CalendarShow(void)
{
  /* Note: need to convert in decimal value in using __LL_RTC_CONVERT_BCD2BIN helper macro */
  /* Display time Format : hh:mm:ss */
  sprintf((char *)aShowTime, "%.2d:%.2d:%.2d", __LL_RTC_CONVERT_BCD2BIN(LL_RTC_TIME_GetHour(RTC)),
          __LL_RTC_CONVERT_BCD2BIN(LL_RTC_TIME_GetMinute(RTC)),
          __LL_RTC_CONVERT_BCD2BIN(LL_RTC_TIME_GetSecond(RTC)));
  /* Display date Format : mm-dd-yy */
  sprintf((char *)aShowDate, "%.2d-%.2d-%.2d", __LL_RTC_CONVERT_BCD2BIN(LL_RTC_DATE_GetMonth(RTC)),
          __LL_RTC_CONVERT_BCD2BIN(LL_RTC_DATE_GetDay(RTC)),
          2000 + __LL_RTC_CONVERT_BCD2BIN(LL_RTC_DATE_GetYear(RTC)));
}

/**
  * @brief  Error executing function.
  * @param  None
  * @retval None
  */
void APP_ErrorHandler(void)
{
  while (1)
  {
  }
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* Users can add their own printing information as needed,
     for example: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* Infinite loop */
  while (1)
  {
  }
}
#endif /* USE_FULL_ASSERT */

/************************ (C) COPYRIGHT Puya *****END OF FILE******************/
